package faf.web;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;

import faf.business.SheetManager;
import faf.business.SurveyManager;
import faf.business.UserManager;
import faf.entities.Account;
import faf.entities.Answer;
import faf.entities.Question;
import faf.entities.Sheet;
import faf.entities.SheetState;
import faf.entities.Survey;
import faf.web.data.SheetForm;

public class SheetController extends SimpleFormController implements Controller {
	UserManager userManager;
	SheetManager sheetManager;
	SurveyManager surveyManager;

	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}

	public void setSheetManager(SheetManager sheetManager) {
		this.sheetManager = sheetManager;
	}

	public void setSurveyManager(SurveyManager surveyManager) {
		this.surveyManager = surveyManager;
	}

	@Override
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Sheet sheet = null;
		try {
			sheet = sheetManager
					.get(Long.parseLong(request.getParameter("id")));
		} catch (NumberFormatException e) {
			// TODO: handle exception
		}
		Account account = (Account) request.getSession().getAttribute("user");
		if (account == null) {
			return new ModelAndView("login");
		}
		if (sheet == null) {
			request.setAttribute("sheet", sheet);
		} else if (sheet.getAccount().getId() == account.getId()) {
			Survey survey = sheet.getSurvey();
			request.setAttribute("questions",
					surveyManager.findListQuestion(survey.getId()));
			request.setAttribute("survey", survey);
			if (sheet.getState() == null)
				sheet.setState(SheetState.PENDING);
			if (sheet.getState().equals(SheetState.PENDING)
					|| sheet.getState().equals(SheetState.REFRESH)) {
				sheet.setState(SheetState.CURRING);
				sheetManager.save(sheet);
			}
			request.setAttribute("sheet", sheet);
		}
		HashMap<String, Object> answered = new HashMap<String, Object>();
		SheetForm sheetForm = new SheetForm();
		if (sheet != null) {
			if (!sheet.getAnswerList().isEmpty()) {
				for (Answer answer : sheet.getAnswerList()) {
					answered.put(String.valueOf(answer.getQuestion().getId()),
							answer.getValue());
				}
			}
		}
		sheetForm.setAnswers(answered);
		request.setAttribute("command", sheetForm);
		request.setAttribute("answered", answered);
		return super.handleRequest(request, response);
	}

	public ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		Account account = (Account) request.getSession().getAttribute("user");
		if (account == null) {
			return new ModelAndView("login");
		}
		if(errors.hasErrors()){
			return new ModelAndView(new RedirectView(getFormView()));
		}
		
		SheetForm sheetForm = (SheetForm) command;

		Sheet sheet = sheetManager.get(sheetForm.getIdSheet());
		Survey survey = sheet.getSurvey();
		List<Question> questions = surveyManager.findListQuestion(survey.getId());
		List<Answer> answers = sheet.getAnswerList();

		if (sheet.getAccount().getId() != account.getId()) {
			return new ModelAndView("home");
		}
		
		int i = 0;
		boolean complete = true;
		for (Question question : questions) {
			Answer answer = null;
			if (answers.size() <= i){
				answer = new Answer();
				answer.setQuestion(question);
				answer.setSheet(sheet);
			} else {
				answer = answers.get(i);
			}
			
			if (sheetForm.getAnswers().get("" + question.getId()) instanceof String) {
				String str = (String) sheetForm.getAnswers().get("" + question.getId());
				answer.setValue(str);
			} else if(sheetForm.getAnswers().get("" + question.getId()) instanceof MultipartFile){
				MultipartFile file = (MultipartFile) sheetForm.getAnswers().get("" + question.getId());
				if(file != null){
					if(! file.isEmpty()){
						System.out.println(">> " + file.getBytes().length);
						answer.setFile(file.getBytes());
						answer.setValue(file.getOriginalFilename());
					}
				}
			}
			
			if(question.isObligatory()&& answer.getValue().isEmpty()){
					complete = false;
			}
			
			if (answers.size() <= i){
				answers.add(answer);
			} else {
				answers.set(i, answer);
			}
			i++;
		}
		
		if (complete){
			sheet.setState(SheetState.COMPLETE);
		}
		
		sheet.setAnswerList(answers);
		sheetManager.save(sheet);

		return new ModelAndView(new RedirectView(getSuccessView()));
	}

	@Override
	protected Object formBackingObject(HttpServletRequest request) {
		SheetForm sheetForm = (SheetForm) request.getAttribute("command");
		try {
			sheetForm.setIdSheet(Integer.parseInt(request.getParameter("id")));
		} catch (NumberFormatException e) {
			// TODO: handle exception
		}
		return sheetForm;
	}

}
